import { Button } from "../ui/button";
import { StatusBadge, TypeBadge } from "./my-badge";
import { Node, useEdges, useNodesData, useReactFlow } from "@xyflow/react";
import { CvNodeData } from "./cv-node";
import { statusConfig, taskTypeColors } from "@/lib/const";
import { Textarea } from "../ui/textarea";
import { Label } from "../ui/label";
import { ImageUpload } from "./image-upload";
import { useMemo } from "react";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "../ui/select";
import { produce } from "immer";

export default function CvNodeDetail({
  id,
  onExecute,
}: {
  id: string;
  onExecute: (id: string) => void;
}) {
  const { data } = useNodesData<Node<CvNodeData>>(id) || {};

  const { getNode } = useReactFlow<Node<CvNodeData>>();

  const edges = useEdges();

  const { textVals, imageVals } = useMemo(() => {
    const textVals: string[] = [];
    const imageVals: string[] = [];
    const edge = edges.find((edge) => edge.target === id);
    if (!edge) return { textVals, imageVals };
    const previousNode = getNode(edge.source);
    if (!previousNode) return { textVals, imageVals };
    previousNode.data.outputs.forEach((output) => {
      if (output.type === "text") {
        textVals.push(output.name);
      } else if (output.type === "image") {
        imageVals.push(output.name);
      }
    });
    return { textVals, imageVals };
  }, [edges, id]);

  const { updateNodeData } = useReactFlow<Node<CvNodeData>>();

  if (!data) {
    return <div>无节点信息</div>;
  }

  return (
    <>
      <div className="flex items-center gap-2">
        <div className="font-semibold w-32 truncate">{data.modelName}</div>
        <span
          className={`inline-block px-2 rounded-full ${
            taskTypeColors[data.task]
          }`}
        >
          {data.task}
        </span>
        <StatusBadge variant={data.status}>
          {statusConfig[data.status!].text}
        </StatusBadge>
      </div>
      <div className="space-y-4 mt-4">
        <h3 className="text-md font-semibold">输入:</h3>
        {data.inputs.map((input, index) => {
          return (
            <div className="space-y-2" key={`${id}-input-${input.name}`}>
              <Label htmlFor={input.name} className="flex items-center gap-2">
                <TypeBadge itemType={input.type} />
                {input.name.replaceAll("_", " ")}
              </Label>
              {input.type === "text" ? (
                textVals.length > 0 ? (
                  <Select
                    value={input.reference}
                    onValueChange={(value: string) => {
                      const newData = produce(data, (draft) => {
                        draft.inputs[index].reference = value;
                      });
                      updateNodeData(id, { inputs: newData.inputs });
                    }}
                  >
                    <SelectTrigger>
                      <SelectValue placeholder="请选择变量" />
                    </SelectTrigger>
                    <SelectContent>
                      {textVals.map((item) => (
                        <SelectItem key={item} value={item}>
                          {item}
                        </SelectItem>
                      ))}
                    </SelectContent>
                  </Select>
                ) : (
                  <Textarea
                    id={input.name}
                    value={input.value}
                    onChange={(e) => {
                      const newData = produce(data, (draft) => {
                        draft.inputs[index].value = e.target.value;
                      });
                      updateNodeData(id, { inputs: newData.inputs });
                    }}
                  />
                )
              ) : input.type === "image" ? (
                imageVals.length > 0 ? (
                  <Select
                    value={input.reference}
                    onValueChange={(value: string) => {
                      const newData = produce(data, (draft) => {
                        draft.inputs[index].reference = value;
                      });
                      updateNodeData(id, { inputs: newData.inputs });
                    }}
                  >
                    <SelectTrigger>
                      <SelectValue placeholder="请选择变量" />
                    </SelectTrigger>
                    <SelectContent>
                      {imageVals.map((item) => (
                        <SelectItem key={item} value={item}>
                          {item}
                        </SelectItem>
                      ))}
                    </SelectContent>
                  </Select>
                ) : (
                  <ImageUpload
                    value={input.value}
                    onChange={(value: string | null) => {
                      const newData = produce(data, (draft) => {
                        draft.inputs[index].value = value || "";
                      });
                      updateNodeData(id, { inputs: newData.inputs });
                    }}
                  />
                )
              ) : null}
            </div>
          );
        })}
      </div>
      <div className="space-x-2">
        {textVals.length === 0 && imageVals.length === 0 && (
          <Button className="mt-4" onClick={() => onExecute(id)}>
            执行
          </Button>
        )}
      </div>
    </>
  );
}
